<template>
  <div class="zb-pro-table" v-loading="loading">
    <div class="footer" :style="{ minHeight: tableHeinght }">
      <!-----------工具栏操作工具----------------->
      <div class="operator">
        <div style="display: flex; justify-content: flex-start">
          <slot name="tabs"></slot>
        </div>
        <div style="display: flex; justify-content: flex-end">
          <slot name="btn"></slot>
        </div>
      </div>
      <!-- ------------表格--------------->
      <div class="table">
        <el-table class="zb-table" @select="selectionChange" @select-all="selectionChange" @sort-change="paixu"
          :row-key="tableData.key" :data="list" :border="border" ref="tableRef">
          <el-table-column type="selection" width="55" v-if="tableData.key" />
          <el-table-column type="index" width="60" label="序号" v-if="tableData.index" header-align="center"
            align="center" />
          <template v-for="item in TableColumns">
            <el-table-column v-bind="{
              ...item,  prop: item.name, align: item.align ? item.align : 'center', headerAlign: 'center' 
            }" v-if="item.slot">
              <template #default="scope">
                <slot :name="item.name" :item="item" :row="scope.row" :index="scope.$index"></slot>
              </template>
            </el-table-column>
            <el-table-column v-else
              v-bind="{ ...item,  prop: item.name, align: item.align ? item.align : 'center', headerAlign: 'center'}" />
          </template>
        </el-table>
      </div>
      <!-- ------------分页--------------->
      <div class="pagination" v-if="props.paging">
        <el-pagination v-model:currentPage="pagination.currentPage" :page-size="pagination.pageSize" background
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100, 500, 1000]" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  getCurrentInstance,
  nextTick,
  onMounted,
  ref,
  watch
} from 'vue';

import qs from 'qs';

import _axios from '@/api/request';

const emit = defineEmits(['paixu'])
let props = defineProps({
  minHeight: {
    type: String,
    default: '660px'
  },
  TableColumns: {
    type: Array,
    default: () => [],
  },
  data: {
    type: Array,
    default: () => [],
  },
  border: {
    type: Boolean,
    default: true
  },
  tableData: {
    type: Object,
    default: {
      formData: {},
      key: '',
      keys: [],
      rows: [],
      url: '',
      type: 'get',
      index: false,//序号
    }
  },
  paging: {
    type: Boolean,
    default: true
  }
})
const { proxy } = <any>getCurrentInstance();
const paginationDefault = {
  currentPage: 1,
  pageSize: 10,
  total: 0
}
const loading = ref(false)
const pagination = ref(JSON.parse(JSON.stringify(paginationDefault)))
const list = ref([])
const tableRef = ref(null)
const tableHeinght = ref(null)

//多选框逻辑处理key
function selectionChange(val) {
  if (val.length > 0) {
    let keys = []
    val.map(item => keys.push(item[props.tableData.key]))
    const rows = val.map(item => {
      return { ...item }
    })
    proxy.tableData.rows = rows
    proxy.tableData.keys = keys
  } else {
    proxy.tableData.rows = []
    proxy.tableData.keys = []
  }
  // if (row === undefined) {
  //   if (val.length > 0) {
  //     let keys = []
  //     let rows = []
  //     val.map(item => {
  //       if (proxy.tableData.keys.indexOf(item[props.tableData.key]) === -1) {
  //         keys.push(item[props.tableData.key])
  //         rows.push(item)
  //       }
  //     })
  //     proxy.tableData.keys = proxy.tableData.keys.concat(keys)
  //     proxy.tableData.rows = proxy.tableData.rows.concat(rows)
  //   } else {
  //     proxy.tableData.keys = []
  //     proxy.tableData.rows = []
  //   }
  // } else {
  //   if (proxy.tableData.keys.indexOf(row[props.tableData.key]) === -1) {
  //     proxy.tableData.keys.push(row[props.tableData.key])
  //     proxy.tableData.rows.push(row)
  //   } else {
  //     proxy.tableData.keys.splice(proxy.tableData.keys.indexOf(row[props.tableData.key]), 1)
  //     proxy.tableData.rows.splice(proxy.tableData.keys.indexOf(row[props.tableData.key]), 1)
  //   }
  // }
}

//重置页码大小到第一页
function resetPagination() {
  pagination.value = JSON.parse(JSON.stringify(paginationDefault))
  initialize()
}

//页码大小，每页多少条
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  initialize()
}

//页码长度，到第几页
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  initialize()
}

function handleToggleSelect() {
  if (props.tableData.keys?.length) {
    nextTick(() => {
      props.tableData.keys.map((key) => {
        list.value.map((item1) => {
          if (key == item1[props.tableData.key]) {
            tableRef.value.toggleRowSelection(item1, true)
          }
        });
      });
    })
  }
}

//排序升序1 降序2 空为取消排序
function paixu(column) {
  emit('paixu', { prop: column.prop, order: column.order === 'ascending' ? 1 : column.order === 'descending' ? 2 : '' })
}
//初始化获取数据列表
function initialize() {
  if (props.data?.length) {
    list.value = props.data
  } else {
    //注入axios来调用接口实现自动化处理
    if (props.tableData?.url) {
      loading.value = true
      const obj = JSON.parse(JSON.stringify(props.tableData.formData))
      if (props.tableData.type == 'get') {
        _axios.get(props.tableData.url, {
          params: {
            ...obj,
            current: pagination.value.currentPage,
            size: pagination.value.pageSize,
            ...props.tableData.formData
          },
          paramsSerializer: params => {
            return qs.stringify(params, { indices: false })
          }
        }).then(res => {
          list.value = res.data.records
          pagination.value.total = res.data.total
          loading.value = false
          if (props.tableData.key) {
            handleToggleSelect()
          }
        }).catch((error) => {
          loading.value = false
        })
      } else {
        _axios({
          url: props.tableData.url,
          method: 'post',
          data: {
            ...obj,
            current: pagination.value.currentPage,
            size: pagination.value.pageSize,
          }
        }).then(res => {
          list.value = res.data.records
          pagination.value.total = res.data.total
          loading.value = false
          if (props.tableData.key) {
            handleToggleSelect()
          }
        }).catch((error) => {
          loading.value = false
        })
      }
    } else {
      list.value = []
    }
  }
}
function hander() {
  let num = document.body.clientHeight - 919 + (props.minHeight.replace('px', '') - 0)
  num = num > 300 ? num : 600
  tableHeinght.value = typeof num === 'number' ? num + 'px' : props.minHeight
}
function loadingMD(val) {
  loading.value = val
}
watch(() => props.data, (val) => {
  list.value = val
})
onMounted(() => {
  hander()
  window.addEventListener('resize', () => {
    hander()
  })
  initialize()
})
defineExpose({
  resetPagination,//重置页码大小到第一页
  initialize,//当前分页查询
  loadingMD,//加载动画
})
</script>
<style scoped lang="scss">
.zb-pro-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .footer {
    flex: 1;
    display: flex;
    // padding: 6px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;

    .operator {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
    }

    .table {
      position: relative;
      flex: 1;
    }

    .zb-table {
      position: absolute;
      height: 100%;
    }
  }

  :deep(.el-drawer__header th) {
    font-size: 15px;
    font-weight: 700;
    color: #252525;
  }

  .pagination {
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 20px;
    box-sizing: border-box;
  }

  :deep(.el-table--default) {
    font-size: 12px;
  }

  :deep(.el-link__inner) {
    font-size: 12px !important;
  }
}
</style>
